const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const unlink = promisify(fs.unlink);

// 支持的图片扩展名
const IMAGE_EXTENSIONS = new Set([
  '.jpg', '.jpeg', '.png', '.gif',
  '.bmp', '.webp', '.tiff', '.svg'
]);

// 创建哈希映射存储唯一图片
const imageHashMap = new Map();

async function findDuplicateImages(directory) {
  const files = await readdir(directory);
  
  for (const file of files) {
    const filePath = path.join(directory, file);
    const fileStat = await stat(filePath);
    
    // 处理子目录
    if (fileStat.isDirectory()) {
      await findDuplicateImages(filePath);
      continue;
    }
    
    // 检查是否为图片文件
    const ext = path.extname(file).toLowerCase();
    if (!IMAGE_EXTENSIONS.has(ext)) continue;
    
    // 计算文件哈希
    const hash = await calculateFileHash(filePath);
    
    if (imageHashMap.has(hash)) {
      const original = imageHashMap.get(hash);
      await handleDuplicate(filePath, original);
    } else {
      imageHashMap.set(hash, filePath);
    }
  }
}

async function calculateFileHash(filePath) {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash('sha256');
    const stream = fs.createReadStream(filePath);
    
    stream.on('data', (chunk) => hash.update(chunk));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', reject);
  });
}

async function handleDuplicate(duplicatePath, originalPath) {
  try {
    console.log(`发现重复图片:
    原始文件: ${originalPath}
    重复文件: ${duplicatePath}`);
    
    // 删除重复文件
    await unlink(duplicatePath);
    console.log(`已删除: ${duplicatePath}`);
    
  } catch (error) {
    console.error(`处理重复文件出错: ${duplicatePath}`, error);
  }
}

// 使用示例
const targetDirectory = process.argv[2] || './images';
findDuplicateImages(targetDirectory)
  .then(() => console.log('去重完成'))
  .catch(err => console.error('处理过程中出错:', err));
